package org.flashIso.engine.base
{
	import org.flashIso.engine.core.ILibrary;
	import org.flashIso.engine.core.ISerializableXML;
	import org.flashIso.engine.core.ValidateableSprite;
	import org.flashIso.engine.objects.IsoImage;
	
	
	/**
	 * 
	 * IsoRoom encapsulates an IsoTiledMap, a background and a foreground.
	 * By default, forground has mouseEnabled and mouseChildren properties set to false.
	 * Use map getter to obtain a reference to IsoTiledMap object. 
	 * 
	 */
	public class IsoRoom extends ValidateableSprite implements ISerializableXML
	{
		
		protected var _background : IsoImage;
		protected var _foreground : IsoImage;
		protected var _map : IsoTiledMap;
		private var _id:String="";
		
		public function IsoRoom()
		{
			_background = new IsoImage();
			addChild(_background);
			
			_map = new IsoTiledMap();
			addChild(_map);
			
			_foreground = new IsoImage();
			_foreground.mouseEnabled = false;
			_foreground.mouseChildren = false;
			addChild(_foreground);
			
		}
		
		public function get id() : String {
			return _id;
		}
		public function set id(value : String) : void {
			if (_id != value){
				_id = value;
				triggerValidation();
			}
		}
		
		public function get background() :IsoImage {
			return _background;
		}
		public function set background(value:IsoImage) :void {
			if (_background != value){
				var level:int = numChildren;
				if (_background != null){
					level = getChildIndex(_background);
					removeChild(_background);
				}
				_background = value;
				if (_background != null){
					addChildAt(_background, level);
				}
				triggerValidation();
			}
		}
		
		public function get foreground() :IsoImage {
			return _foreground;
		}
		public function set foreground(value:IsoImage) :void {
			if (_foreground != value){
				var level:int = numChildren;
				if (_foreground != null){
					level = getChildIndex(_foreground);
					removeChild(_foreground);
				}
				_foreground = value;
				if (_foreground != null){
					_foreground.mouseEnabled = false;
					_foreground.mouseChildren = false;
					addChildAt(_foreground, level);
				}
				triggerValidation();
			}
		}
		
		/**
		 * 
		 * Getter for the IsoTiledMap instance of the room.
		 * 
		 **/
		public function get map() : IsoTiledMap {
			return _map;
		}
		
		public function toXML() : XML {
			var xml:XML = <IsoRoom />;
			
			xml.@id = id;
			
			var i:uint;
			for (i = 0; i < numChildren; i++ ) {
				if (getChildAt(i) is ISerializableXML) {
					xml.appendChild((getChildAt(i) as ISerializableXML).toXML());
				}
			}
			return xml;
		}
		
		public function fromXML(xml:XML, library:ILibrary = null) : void {
			id = (xml.@id + "");
			background.fromXML(xml.children()[0], library);
			map.fromXML(xml.children()[1], library);
			foreground.fromXML(xml.children()[2], library);
		}
	}
}